import os

import pymysql

from conf import Conf


def read_sqls(*sqlfiles):  # 读指定的sql文件sqlfile将所有有效sql语句存入列表并返回；如果不给参数则读取当前文件夹中所有sql文件中的sql语句
    if not sqlfiles:  # 没给参数
        sqlfiles = [i for i in os.listdir('../initsqls/') if i.endswith('.sql')]
    # print(sqlfiles)
    sqls = []
    # 否则，sqlfiles中本来就存着很多文件名
    for sfile in sqlfiles:
        file = open('../initsqls/'+sfile, 'r', encoding='utf-8')
        for sql in file:
            if sql.strip() and not sql.startswith('--'):
                sqls.append(sql.strip())
    return sqls


class DB:  # 构造方法，用于连接数据库，将数据库连接对象和游标存入私有成员变量
    def __init__(self):  # 构造方法
        dbinfo = Conf().dbinfo
        self.__conn = pymysql.connect(**dbinfo)
        self.__cursor = self.__conn.cursor()

    def init_db(self, *sqlfiles):  # 初始化数据库
        sqls = read_sqls(*sqlfiles)
        # print(sqls)
        for sql in sqls:
            self.__cursor.execute(sql)
        self.__conn.commit()

    def checkdb(self, case_info, args, check_sql, expect_rows):  # 落库检查
        self.__cursor.execute(check_sql)
        actual_rows = self.__cursor.fetchone()[0]
        if actual_rows == expect_rows:
            print(f'{case_info}==落库检查通过')
        else:
            print(f'{case_info}==落库检查失败==要检查的数据：{args}==预期行数：{expect_rows}==实际行数：{actual_rows}')
            self.__conn.close()


if __name__ == '__main__':
    # print(read_sqls('login.sql'))
    # DB().init_db('signup.sql')
    DB().checkdb('总行数',{'a':1},'select count(*) from users',6)
 
